<?php



declare (strict_types=1);

namespace app\index\controller;

use app\mall\model\MallGoods;
use app\mall\model\MallUserActionCollect;
use app\mall\service\UserAction;
use think\admin\helper\QueryHelper;
use think\db\Query;

/**
 * 用户收藏数据
 * @class Collect
 * @package plugin\wemall\controller\api\auth\action
 */
class Collect  extends Base
{
    /**
     * 设置收藏记录
     * @return void
     * @throws \think\db\exception\DbException
     */
    public function set()
    {
        $this->check_login();
        $data = $this->_vali([
            'uid.value'    => $this->uid,
            'gcode.require' => 'GOODS_REQUIRE'
        ]);
        $map = ['code' => $data['gcode'], 'deleted' => 0];
        $goods = MallGoods::mk()->where($map)->findOrEmpty();

        if ($goods->isExists()) {
            UserAction::set($this->uid, $data['gcode'], 'collect');
            $this->success('COLLECT_SUCCESS');
        } else {
            $this->error('GOODS_NOT_FOUND');
        }
    }

    /**
     * 取消收藏记录
     * @return void
     */
    public function cancel_collect(){
        $this->check_login();
        $data = $this->_vali([
            'uid.value'    => $this->uid,
            'id.require' => 'ID REQUIRE'
        ]);
        if(!$collect = MallUserActionCollect::mk()->where(['id'=>$data['id'],'unid'=>$this->uid])->find()){
            $this->error('COLLECT_NOT_FOUND');
        }
        if ($collect->delete()) {
            $this->success('CANCEL_COLLECT_SUCCESS');
        } else {
            $this->error('COLLECT_NOT_FOUND');
        }

    }
    /**
     * 获取我的搜索记录
     * @return void
     */
    public function get()
    {
        MallUserActionCollect::mQuery(null, function (QueryHelper $query) {
            // 关联商品信息
            $query->order('sort desc')->with(['goods' => function (Query $query) {
                $query->field('code,name,cover,stock_sales,stock_virtual,price_selling,status,deleted');
            }]);
            // 搜索商品信息
            $db = MallGoods::mQuery()->like('name#keys');
            $query->whereRaw("gcode in {$db->field('code')->buildSql()}");
            $query->where(['unid' => $this->unid])->like('gcode');
            [$page, $limit] = [intval(input('page', 1)), intval(input('limit', 10))];
            $this->success('我的收藏记录！', $query->page($page, false, false, $limit));
        });
    }

    /**
     * 删除收藏记录
     * @return void
     * @throws \think\db\exception\DbException
     */
    public function del()
    {
        $data = $this->_vali(['gcode.require' => '商品不能为空！']);
        UserAction::del($this->unid, $data['gcode'], 'collect');
        $this->success('删除记录成功！');
    }

    /**
     * 清空收藏记录
     * @return void
     * @throws \think\db\exception\DbException
     */
    public function clear()
    {
        MallUserActionCollect::mk()->where(['unid' => $this->unid])->delete();
        UserAction::clear($this->unid, 'collect');
        $this->success('清理记录成功！');
    }
}